package com.ews.onlineexchange.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.DeterminedRecord;
import com.ews.onlineexchange.model.Notification;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.Trade;
import com.ews.onlineexchange.model.User;

@Named
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class NotificationService {
	
	static DateFormat df;
	static {
		df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	}
	
	@Inject
	EntityManager entityManager;
	
	public void sendSuccessNotification(Bulletin bulletin) {
	}
	
	public void sendInModificationNotification(Bulletin bulletin,ServiceSupplier supplier) {
		StringBuilder title = new StringBuilder();
		title.append("关于无法收到【");
		title.append(bulletin.getProjectName());
		title.append("】邀请的通知");
		StringBuilder content = new StringBuilder();
		content.append("\n")
						.append((supplier.getCnname()))
//						.append("，您好:\n")
						.append( "，现暂停你公司参与项目选取资格，待整改合格并提报诚信承诺书后，恢复项目选取资格。" );
//						.append("由于您近期的出勤率检查考核中未达到要求，所以您无法收到本次项目的邀请，请按照要求进行整改。给您带来的不便，我们深感抱歉！");
		  Notification no = new Notification();
		  no.setTitile(title.toString());
		  no.setBulletin(bulletin);
		  no.setContent(content.toString());
		  no.setHasRead(false);
		  no.setSendDate(new Date());
		  no.setReceiver(supplier);
		  entityManager.persist(no);
	}
	
	public void sendCancelAppliedBulletinNotification(Bulletin bulletin,ServiceSupplier supplier) {
		StringBuilder title = new StringBuilder();
		title.append("关于系统自动取消【");
		title.append(bulletin.getProjectName());
		title.append("】报名的通知");
		StringBuilder content = new StringBuilder();
		content.append("\n")
						.append((supplier.getCnname()))
						.append( "，现暂停你公司参与项目选取资格，待整改合格并提报诚信承诺书后，恢复项目选取资格。" );
//						.append("，您好:\n")
//						.append("由于您近期的出勤率检查考核中未达到要求，所以系统会自动取消您已报名但未选取的公告的报名，请按照要求进行整改。给您带来的不便，我们深感抱歉！");
		  Notification no = new Notification();
		  no.setTitile(title.toString());
		  no.setBulletin(bulletin);
		  no.setContent(content.toString());
		  no.setHasRead(false);
		  no.setSendDate(new Date());
		  no.setReceiver(supplier);
		  entityManager.persist(no);
	}
	
	
	public void sendFailNotification(Bulletin bulletin) {
		StringBuilder failTitle = new StringBuilder();
		failTitle.append("【");
		failTitle.append(bulletin.getSuccessTrade().getBulletin().getProjectName());
		failTitle.append("】未中选通知");
		Trade successTrade = bulletin.getSuccessTrade();
		for (Trade trade : bulletin.getTrades()) {//报名未中选的中介
			if (trade.isHasVerify() && trade.isApply() && !trade.getId().equals(successTrade.getId())) {
				StringBuilder failContent = new StringBuilder();
				failContent.append("\n")
								.append(trade.getSupplier().getCnname())
								.append("，您好:\n")
								.append("您在东营市网上中介超市报名参与的【")
								.append(bulletin.getProjectName())
								.append("】，项目编号【")
								.append(bulletin.getSerialNumber())
								.append("】已经选取完成，很遗憾您未中选。");
				  Notification no = new Notification();
				  no.setTitile(failTitle.toString());
				  no.setBulletin(bulletin);
				  no.setContent(failContent.toString());
				  no.setHasRead(false);
				  no.setReceiver(trade.getSupplier());
				  no.setSendDate(new Date());
				  entityManager.persist(no);
			}
				
		}
	}
	
	public void sendNotification(String title,Bulletin bulletin,String content,User user) {
		Notification no = new Notification();
		  no.setTitile(title);
		  no.setBulletin(bulletin);
		  no.setContent(content);
		  no.setHasRead(false);
		  no.setReceiver(user);
		  no.setSendDate(new Date());
		  entityManager.persist(no);
	}
	
	public void sendHandleNotification(DeterminedRecord record) {
		User reporter = record.getUndeterminedRoster().getEnteringUser();
		ServiceSupplier suppier = record.getSupplier();
		StringBuilder title = new StringBuilder();
		title.append("您有一条关于【");
		title.append(suppier.getCnname());
		title.append("】中介的待定名单需要处理！");
		StringBuilder content = new StringBuilder();
		content.append("\n")
						.append(reporter.getCnname())
						.append("，您好:\n")
						.append("您在")
						.append(df.format(record.getUndeterminedRoster().getEnteringDate()))
						.append("上报的关于【")
						.append(suppier.getCnname())
						.append("】中介的待定名单目前可以处理，请您及时处理。");
		  Notification no = new Notification();
		  no.setTitile(title.toString());
		  no.setBulletin(null);
		  no.setContent(content.toString());
		  no.setHasRead(false);
		  no.setReceiver(reporter);
		  no.setSendDate(new Date());
		  entityManager.persist(no);
	}
	
	/**其他地方已有
	 * @param trade
	 */
	public void addCancelAppliedByBuyerMessageToSupplier(Trade trade) {
	}
	
	@Inject
	UserService userService;
	private final static String GET_NOTIFICATION_TOTAL_COUNT = ""
			+ " SELECT COUNT(no)"
			+ " FROM Notification no "
			+ " WHERE no.delFlag = 0 "
			+ " AND no.receiver.id = :userId ";
	public Long  getNotificationTotalCount() {
		User loginedUser = userService.getLoginedUser();
		if(loginedUser == null) return 0l;
		Query query = entityManager.createQuery(GET_NOTIFICATION_TOTAL_COUNT);
			query.setParameter("userId", loginedUser.getId());
		return (Long)query.getSingleResult();
	}
	
	private final static String GET_NOT_READ_NOTIFICATION_TOTAL_COUNT = ""
			+ " SELECT COUNT(no)"
			+ " FROM Notification no "
			+ " WHERE no.delFlag = 0 "
			+ "	AND no.hasRead = 0 "
			+ " AND no.receiver.id = :userId ";
	public Long  getNotReadNotificationTotalCount() {
		User loginedUser = userService.getLoginedUser();
		if(loginedUser == null) return 0l;
		Query query = entityManager.createQuery(GET_NOT_READ_NOTIFICATION_TOTAL_COUNT);
			query.setParameter("userId", loginedUser.getId());
		return (Long)query.getSingleResult();
	}
	
	public Long  getNotReadNotificationCountByUserId(String userId) {
		Query query = entityManager.createQuery(GET_NOT_READ_NOTIFICATION_TOTAL_COUNT);
			query.setParameter("userId", userId);
		return (Long)query.getSingleResult();
	}
}
